package bbk.nfc;

import java.io.IOException;

import bbk.nfc.opt.OptSetting;

import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import android.widget.Toast;

public class NfcRW
{
	public static final String TAG = "NFC_RW";
	
	public static String readNFC(Intent intent,Context context)
	{
		Log.i(TAG, "readNFC:" + intent);
		Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		if(myTag == null)return "error";
		if(rawMsgs == null)return "error";

		String s = "";
		s +=readTag(myTag);
		s += "\n message length: " + rawMsgs.length;
		if (rawMsgs != null)
		{
			NdefMessage msgs[] = new NdefMessage[rawMsgs.length];
			for (int i = 0; i < rawMsgs.length; i++)
			{
				msgs[i] = (NdefMessage) rawMsgs[i];
				NdefRecord[] records = msgs[i].getRecords();
				s+="\n";
				s += "\n message " + i + ":begin records length: " + records.length;
				for(int j=0;j < records.length;j++ )
				{
					s += "\n \t records" + j + ":begin" ;
					s += "\n \t records id:" + new String(records[j].getId());
					s += "\n \t records Payload Hex:" + NfcUtils.toHexStringR(records[j].getPayload());
					s += "\n \t records Payload String:" + new String(records[j].getPayload());
					s += "\n \t records Tnf:" + records[j].getTnf();
					s += "\n \t records Type:" + new String(records[j].getType());
					s += "\n \t records" + j + ":end" ;
					procRecord(records[j],context);
				}
				s += "\n  message" + i + ":end \n" ;
			}
		}
		return s;
	}
	
	public static String readTag(Tag tag)
	{
		String s = "\n tag ID:" + NfcUtils.toHexStringR(tag.getId());
		String []list = tag.getTechList();
		for(String l:list)
		{
			s += "\n tag tech list:" + l;
		}
		s+="\n";
		return s;
	}

	public static void procRecord(NdefRecord record,Context context)
	{
		byte[] pl = record.getPayload();
		switch(record.getTnf())
		{
			case NdefRecord.TNF_EXTERNAL_TYPE:
				if(pl[0]== 0x32)
				{
					OptSetting.toggleWifi(pl[2], context);
				}
				else if(pl[0]== 0x31)
				{
					OptSetting.toggleBT(pl[2]);
				}
				break;
		}
	}
	
	private static NdefMessage getEmptyMsg()
	{
		NdefRecord r0 =null;
		r0 = new NdefRecord(NdefRecord.TNF_EMPTY, null, null, null);
		return new NdefMessage(new NdefRecord[]{ r0 });
	}
	
	public static boolean formateTag(Tag tag,Context context)
	{
		NdefMessage msg = getEmptyMsg();
		return writeTag(msg,tag,context);
	}
	public static boolean writeTag(NdefMessage message, Tag tag,Context context)
	{
		if(message == null)return false;
		int size = message.toByteArray().length;
		try
		{
			Ndef ndef = Ndef.get(tag);
			if (ndef != null)
			{
				ndef.connect();
				
				if (!ndef.isWritable())
				{
					toast("Tag is read-only.",context);
					return false;
				}
				if (ndef.getMaxSize() < size)
				{
					toast("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.",context);
					return false;
				}
				
				ndef.writeNdefMessage(message);
				toast("д����ݳɹ�.",context);
				return true;
			}
			else
			{
				NdefFormatable format = NdefFormatable.get(tag);
				if (format != null)
				{
					try
					{
						format.connect();
						format.format(message);
						toast("Formatted tag and wrote message",context);
						return true;
					}
					catch (IOException e)
					{
						toast("Failed to format tag.",context);
						return false;
					}
				}
				else
				{
					toast("Tag doesn't support NDEF.",context);
					return false;
				}
			}
		}
		catch (Exception e)
		{
			toast("д�����ʧ��",context);
		}
		finally
		{
		}
		return false;
	}
	private static void toast(String text,Context context)
	{
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}
}
